package com.getpebble.android.main.sections.settings.fragment;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.Music;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.framework.PblFrameworkInterface;
import com.getpebble.android.framework.developer.PblDeviceObserver.ConnectedDeviceChangeListener;
import com.getpebble.android.framework.util.PebbleCapabilities;
import com.getpebble.android.main.sections.settings.SettingsUtil;
import com.getpebble.android.util.LocaleUtil;
import com.getpebble.android.util.StringUtil;
import java.util.List;

public class SettingsFragment extends PreferenceFragment implements OnPreferenceChangeListener, ConnectedDeviceChangeListener {
    public static final String TAG = SettingsFragment.class.getSimpleName();
    private static final Handler sHandler = new Handler(Looper.getMainLooper());
    private Preference mAnalyticsPreference = null;
    private Preference mAutoAppUpdateNotificationPreference = null;
    private Preference mAutoAppUpdatePreference = null;
    private Preference mAutoAppUpdateWiFiPreference = null;
    private Preference mDeveloperConnPreference = null;
    private Preference mIntervalPreference = null;
    private Preference mLanguagePreference = null;
    private List<ResolveInfo> mMusicApps = null;
    private CharSequence[] mMusicKeys = null;
    private ListPreference mMusicPreference = null;
    private CharSequence[] mMusicValues = null;
    private PblPreferences mPblPreferences = null;
    private Preference mVersionPreference = null;

    public void onDestroy() {
        super.onDestroy();
        PebbleApplication.removeConnectedDeviceChangeListener(this);
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getPreferenceManager().setSharedPreferencesName("PEBBLE_PREFERENCES");
        addPreferencesFromResource(R.xml.main_settings);
        configureMusicControl();
        SettingsUtil.addBuildSpecificPreferences(this);
        this.mPblPreferences = new PblPreferences(PebbleApplication.getAppContext());
        this.mVersionPreference = findPreference(this.mPblPreferences.prefKeyToString(PrefKey.VERSION));
        this.mIntervalPreference = findPreference(this.mPblPreferences.prefKeyToString(PrefKey.SYNC_INTERVAL));
        this.mDeveloperConnPreference = findPreference(this.mPblPreferences.prefKeyToString(PrefKey.DEVELOPER_CONNECTION));
        this.mMusicPreference = (ListPreference) findPreference(this.mPblPreferences.prefKeyToString(PrefKey.MUSIC_TARGET));
        this.mAnalyticsPreference = findPreference(this.mPblPreferences.prefKeyToString(PrefKey.ANALYTICS_OPTIN));
        this.mLanguagePreference = findPreference(this.mPblPreferences.prefKeyToString(PrefKey.LANGUAGE_PACK_CATEGORY));
        this.mLanguagePreference.setShouldDisableView(true);
        this.mAutoAppUpdatePreference = findPreference(this.mPblPreferences.prefKeyToString(PrefKey.AUTO_APP_UPDATES_ENABLED));
        this.mAutoAppUpdateNotificationPreference = findPreference(this.mPblPreferences.prefKeyToString(PrefKey.AUTO_APP_UPDATES_NOTIFICATIONS));
        this.mAutoAppUpdateWiFiPreference = findPreference(this.mPblPreferences.prefKeyToString(PrefKey.AUTO_APP_UPDATES_WIFI_ONLY));
        setAutoAppUpdateCheckBoxesSelectable(this.mPblPreferences.getBooleanData(PrefKey.AUTO_APP_UPDATES_ENABLED, true));
        setVersionSummary();
        setIntervalSummary();
        setIntervalChangeListener();
        setDeveloperConnChangeListener();
        setAnalyticsOptInChangeListener();
        setAutoAppUpdateChangeListener();
        PebbleApplication.addConnectedDeviceChangeListener(this);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        view.setBackgroundColor(getResources().getColor(R.color.preferences_background_color));
        return view;
    }

    public void onResume() {
        super.onResume();
        updateLanguagePreference();
    }

    private void setDeveloperConnChangeListener() {
        if (this.mDeveloperConnPreference != null) {
            this.mDeveloperConnPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference preference, Object object) {
                    Boolean devConnOn = (Boolean) object;
                    if (devConnOn.booleanValue()) {
                        MobileAppBehavior.logDeveloperModeOn();
                    } else {
                        MobileAppBehavior.logDeveloperModeOff();
                    }
                    new PblPreferences(PebbleApplication.getAppContext()).setBooleanData(PrefKey.DEVELOPER_CONNECTION, devConnOn.booleanValue());
                    PblFrameworkInterface frameworkInterface = PebbleApplication.getFrameworkInterface();
                    if (frameworkInterface != null) {
                        if (devConnOn.booleanValue()) {
                            frameworkInterface.startDeveloperConnection();
                        } else {
                            frameworkInterface.stopDeveloperConnection();
                        }
                    }
                    return true;
                }
            });
        }
    }

    private void setAnalyticsOptInChangeListener() {
        if (this.mAnalyticsPreference != null) {
            this.mAnalyticsPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference preference, Object object) {
                    Boolean analyticsOptIn = (Boolean) object;
                    if (SettingsFragment.this.getActivity() == null) {
                        Trace.error(SettingsFragment.TAG, "setAnalyticsOptInChangeListener(): activity was null");
                        return false;
                    }
                    new PblPreferences(SettingsFragment.this.getActivity()).setBooleanData(PrefKey.ANALYTICS_OPTIN, analyticsOptIn.booleanValue());
                    PblFrameworkInterface frameworkInterface = PebbleApplication.getFrameworkInterface();
                    if (frameworkInterface != null) {
                        frameworkInterface.sendAnalyticsEnableDisableRequest(analyticsOptIn.booleanValue());
                    }
                    return true;
                }
            });
        }
    }

    private void setAutoAppUpdateChangeListener() {
        if (this.mAutoAppUpdatePreference == null) {
            Trace.error(TAG, " Failed to set auto app update listener: mAutoAppUpdatePreference was null");
        } else {
            this.mAutoAppUpdatePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference preference, Object object) {
                    Boolean autoAppUpdatesEnabled = (Boolean) object;
                    new PblPreferences(PebbleApplication.getAppContext()).setBooleanData(PrefKey.AUTO_APP_UPDATES_ENABLED, autoAppUpdatesEnabled.booleanValue());
                    SettingsFragment.this.setAutoAppUpdateCheckBoxesSelectable(autoAppUpdatesEnabled.booleanValue());
                    return true;
                }
            });
        }
    }

    private void setAutoAppUpdateCheckBoxesSelectable(boolean enabled) {
        this.mAutoAppUpdateNotificationPreference.setEnabled(enabled);
        this.mAutoAppUpdateWiFiPreference.setEnabled(enabled);
        this.mAutoAppUpdateNotificationPreference.setSelectable(enabled);
        this.mAutoAppUpdateWiFiPreference.setSelectable(enabled);
    }

    private void setMusicSummary() {
        if (this.mMusicPreference != null) {
            CharSequence entry = this.mMusicPreference.getEntry();
            if (entry != null) {
                this.mMusicPreference.setSummary(entry.toString());
            }
        }
    }

    private void setVersionSummary() {
        if (this.mVersionPreference != null) {
            this.mVersionPreference.setSummary("2.4.1");
        }
    }

    private void setIntervalSummary() {
        SettingsUtil.setIntervalSummary(this.mIntervalPreference, this.mPblPreferences, getResources());
    }

    private void setIntervalChangeListener() {
        if (this.mIntervalPreference != null) {
            this.mIntervalPreference.setOnPreferenceChangeListener(this);
        }
    }

    private void setMusicChangeListener() {
        if (this.mMusicPreference != null) {
            this.mMusicPreference.setOnPreferenceChangeListener(this);
        }
    }

    private void configureMusicControl() {
        final Activity activity = getActivity();
        if (activity != null) {
            new PblAsyncTask() {
                public boolean doInBackground() {
                    PackageManager pm = activity.getPackageManager();
                    SettingsFragment.this.mMusicApps = Music.getMediaReceivers(pm, false);
                    SettingsFragment.this.mMusicKeys = new CharSequence[(SettingsFragment.this.mMusicApps.size() + 1)];
                    SettingsFragment.this.mMusicValues = new CharSequence[(SettingsFragment.this.mMusicApps.size() + 1)];
                    SettingsFragment.this.mMusicKeys[0] = "";
                    SettingsFragment.this.mMusicValues[0] = SettingsFragment.this.getString(R.string.pref_music_none);
                    for (int i = 0; i < SettingsFragment.this.mMusicApps.size(); i++) {
                        ResolveInfo info = (ResolveInfo) SettingsFragment.this.mMusicApps.get(i);
                        if (!(info == null || info.activityInfo == null)) {
                            SettingsFragment.this.mMusicKeys[i + 1] = info.activityInfo.packageName;
                            SettingsFragment.this.mMusicValues[i + 1] = Music.getAppName(info, pm);
                        }
                    }
                    SettingsFragment.sHandler.post(new Runnable() {
                        public void run() {
                            ListPreference musicTargets = (ListPreference) SettingsFragment.this.getPreferenceScreen().findPreference(SettingsFragment.this.mPblPreferences.prefKeyToString(PrefKey.MUSIC_TARGET));
                            if (musicTargets != null) {
                                musicTargets.setEntryValues(SettingsFragment.this.mMusicKeys);
                                musicTargets.setEntries(SettingsFragment.this.mMusicValues);
                            }
                            SettingsFragment.this.setMusicSummary();
                            SettingsFragment.this.setMusicChangeListener();
                        }
                    });
                    return true;
                }

                public void onTaskSuccess() {
                }

                public void onTaskFailed() {
                }
            }.submit();
        }
    }

    public boolean onPreferenceChange(Preference preference, Object newValue) {
        String key = preference.getKey();
        if (key == null) {
            return false;
        }
        if (key.equalsIgnoreCase(this.mPblPreferences.prefKeyToString(PrefKey.SYNC_INTERVAL))) {
            PebbleApplication.getSyncManager().setPeriodicSync();
            sHandler.post(new Runnable() {
                public void run() {
                    SettingsFragment.this.setIntervalSummary();
                }
            });
            return true;
        } else if (!key.equalsIgnoreCase(this.mPblPreferences.prefKeyToString(PrefKey.MUSIC_TARGET))) {
            return false;
        } else {
            sHandler.post(new Runnable() {
                public void run() {
                    SettingsFragment.this.setMusicSummary();
                }
            });
            return true;
        }
    }

    public void notifyConnectedDeviceChanged() {
        Trace.debug(TAG, "notifyConnectedDeviceChanged()");
        sHandler.post(new Runnable() {
            public void run() {
                SettingsFragment.this.updateLanguagePreference();
            }
        });
    }

    private void updateLanguagePreference() {
        Trace.debug(TAG, "updateLanguagePreference()");
        if (isResumed()) {
            PblDeviceRecord record = PebbleApplication.getConnectedDeviceRecord();
            boolean isEnabled = record != null && PebbleCapabilities.remoteSupportsLanguagePacks(record.fwVersion);
            this.mLanguagePreference.setEnabled(isEnabled);
            if (isEnabled) {
                String language = LocaleUtil.getLanguageForDevice(record);
                Activity activity = getActivity();
                if (activity == null) {
                    Trace.debug(TAG, "Cannot set preference with null parent activity");
                    return;
                } else {
                    this.mLanguagePreference.setSummary(activity.getResources().getString(R.string.language_selection_selected_language) + ": " + StringUtil.capitalize(language));
                    return;
                }
            }
            this.mLanguagePreference.setSummary("");
            return;
        }
        Trace.debug(TAG, "SettingsFragment not resumed; not updating language preference");
    }
}
